﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace L11
{
    public partial class FrmMain : Form
    {
        private Bitmap bmAll;//原始位图
        private Bitmap[] bmFragments = new Bitmap[48];//动画帧位图
        private int displayIndex = 0;//起始帧索引

        public FrmMain()
        {
            InitializeComponent();
        }

        private void FrmMain_Load(object sender, EventArgs e)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat(
                "窗体大小（像素）：{0},{1}",
                this.Width.ToString(),
                this.Height.ToString()
                );
            sb.AppendLine();
            sb.AppendFormat(
                "工作区域大小（像素）：{0},{1}",
                this.ClientRectangle.Width.ToString(),
                this.ClientRectangle.Height.ToString()
                );
            MessageBox.Show(sb.ToString(), "信息提示");

            //初始化动画位图资源:载入大图，然后再分割，来减少IO带来的资源消耗
            bmAll = new Bitmap(Application.StartupPath + "\\threerings.bmp");
            for (int row = 0; row < 8; row++)
            {
                for (int col = 0; col < 6; col++)
                {
                    bmFragments[row * 6 + col] = bmAll.Clone(
                        new Rectangle(col * 75, row * 75, 75, 75),
                        bmAll.PixelFormat);
                }
            }
            //初始化计时器Timer2
            this.timer1.Interval = 80;
            this.timer1.Start();

        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            //动画逻辑
            displayIndex = (++displayIndex) % 48;
            if (displayIndex == 47 && this.timer1.Interval >= 20)
            {
                this.timer1.Interval -= 10;
            }
            //刷新界面
            this.Invalidate();
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            //预先在内存中绘制所有内容，再一次性绘制到前端
            Bitmap buff = new Bitmap(this.ClientRectangle.Width, this.ClientRectangle.Height);
            Graphics g = Graphics.FromImage(buff);
            //绘制到缓冲区（内存）
            g.DrawImage(bmFragments[displayIndex], new PointF(200, 180));
            //绘制到前端
            e.Graphics.DrawImage(buff, 0, 0);
            //释放缓冲区内存
            g.Dispose();
            base.OnPaint(e);
        }
    }
}
